package com.nudt.anbot2.actions;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.nudt.anbot2.BaseActivity;
import com.nudt.anbot2.MainActivity;
import com.willblaschko.android.alexa.audioplayer.AlexaAudioPlayer;
import com.willblaschko.android.alexa.interfaces.AvsItem;
import com.willblaschko.android.alexa.interfaces.speechrecognizer.AvsStopCaptureItem;
import com.willblaschko.android.alexa.requestbody.DataRequestBody;
import com.nudt.anbot2.BuildConfig;
import com.nudt.anbot2.R;
import com.willblaschko.android.recorderview.RecorderView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;

import ee.ioc.phon.android.speechutils.AudioRecorder;
import ee.ioc.phon.android.speechutils.RawAudioRecorder;
import okio.BufferedSink;


/**
 * @author will on 5/30/2016.
 */

public class SendAudioActionFragment extends BaseListenerFragment {

    private static final String TAG = "SendAudioActionFragment";

    private final static int MY_PERMISSIONS_REQUEST_RECORD_AUDIO = 1;
    private static final int AUDIO_RATE = 16000;
    private RawAudioRecorder recorder;
    private RecorderView recorderView;

    // 超时处理
    private Handler delayHandler = new Handler(Looper.getMainLooper());


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_action_audio, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recorderView = (RecorderView) view.findViewById(R.id.recorder);
        recorderView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(recorder == null) {
                    Log.i(TAG, "click startListening");
                    startListening();
                }else{
                    Log.i(TAG, "click stopListening");
                    stopListening();
                }
            }
        });

        EventBus.getDefault().register(this);

    }

    @Override
    public void onResume() {
        super.onResume();

        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.RECORD_AUDIO)) {
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.RECORD_AUDIO},
                        MY_PERMISSIONS_REQUEST_RECORD_AUDIO);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_RECORD_AUDIO: {
                // If request is cancelled, the result arrays are empty.
                if (!(grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED)){
                    getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
                }
            }

        }
    }

    @Override
    public void onStop() {
        super.onStop();
        delayHandler.removeCallbacksAndMessages(null);
        alexaManager.cancelAudioRequest();

        // 设置为完成状态
        MainActivity mainActivity = (MainActivity) getActivity();
        if (mainActivity != null) {
            mainActivity.stateFinished();
        }

        //tear down our recorder on stop
        if(recorder != null){
            recorder.stop();
            recorder.release();
            recorder = null;
        }
    }

    @Override
    public void startListening() {
        delayHandler.removeCallbacksAndMessages(null);

        alexaManager.cancelAudioRequest();
        Log.i(TAG, "startListening");
        clearDirective();

        if(recorder == null){
            recorder = new RawAudioRecorder(AUDIO_RATE);
        }
        recorder.start();

//        delayHandler.postDelayed(new Runnable(){
//            public void run() {
//                Log.i(TAG, "语音处理超时");
//                Toast.makeText(getContext(), "语音处理超时", Toast.LENGTH_SHORT);
//                stopListening();
//            }
//        }, 5000);   //5秒

        alexaManager.sendAudioRequest(requestBody, getRequestCallback());
    }

    // clear voice queue and close player
    private void clearDirective() {
        BaseActivity activity = (BaseActivity) getActivity();
        if (activity != null && activity.getAvsQueue() != null) {
            activity.getAvsQueue().clear();
        }

        if(activity != null && activity.getAudioPlayer() != null){
            activity.getAudioPlayer().stop();
        }
    }


    private DataRequestBody requestBody = new DataRequestBody() {
        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            while (recorder != null && recorder.getState() != AudioRecorder.State.ERROR && !recorder.isPausing()) {
                if(recorder != null) {
                    final float rmsdb = recorder.getRmsdb();
                    if(recorderView != null) {
                        recorderView.post(new Runnable() {
                            @Override
                            public void run() {
                                recorderView.setRmsdbLevel(rmsdb);
                            }
                        });
                    }
                    if(sink != null && recorder != null) {
                        sink.write(recorder.consumeRecording());
                    }
                    if(BuildConfig.DEBUG){
                        //Log.i(TAG, "Received audio");
                        //Log.i(TAG, "RMSDB: " + rmsdb);
                    }
                }

                try {
                    Thread.sleep(25);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //Log.i(TAG, "while process recorder != null : " + (recorder != null));
                //Log.i(TAG, "while process recorder.getState() != AudioRecorder.State.ERROR : " + (recorder != null && recorder.getState() != AudioRecorder.State.ERROR));
                //Log.i(TAG, "while process !recorder.isPausing() : " + (recorder != null && !recorder.isPausing()));

            }

            stopListening();
        }

    };

    private void stopListening(){
        Log.i(TAG, "stopListening");
        clearDirective();

        if(recorder != null) {
            recorder.stop();
            recorder.release();
            recorder = null;
        }
    }

    @Override
    protected String getTitle() {
        return getString(R.string.fragment_action_send_audio);
    }

    @Override
    protected int getRawCode() {
        return R.raw.code_audio;
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void AvsItemEvent(AvsItem avsItem) {
        Log.i(TAG, "AvsItemEvent");
        if (avsItem instanceof AvsStopCaptureItem) {
            Log.i(TAG, "recv AvsStopCaptureItem");
            stopListening();
        }
    }
}
